package com.huahua.api.service.impl;

import com.google.common.collect.Lists;
import com.huahua.api.entity.developTool.github.dto.GitBranchesDTO;
import com.huahua.api.entity.developTool.github.vo.GithubGetBranchListVO;
import com.huahua.api.entity.developTool.github.vo.GithubObtainInfoVo;
import com.huahua.api.entity.param.GithubBaseParam;
import com.huahua.api.enums.GitBranchType;
import com.huahua.api.enums.GithubAddressTypeEnum;
import com.huahua.api.enums.LocalDirEnum;
import com.huahua.api.exception.CommonException;
import com.huahua.api.service.GithubService;
import com.huahua.api.util.CheckUtil;
import com.huahua.api.util.GitUtils;
import com.huahua.api.util.OwnFileUtil;
import com.huahua.api.util.OwnGithubUtil;
import org.dromara.hutool.core.compress.ZipUtil;
import org.dromara.hutool.core.io.file.FileUtil;
import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.http.client.HttpDownloader;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.transport.CredentialsProvider;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author LoveHuaHua
 * @date 2025年02月27日 20:45
 * @description believe in yourself
 */
@Service
public class GithubServiceImpl implements GithubService {
    /**
     * 根据github地址 返回该地址的类型
     *
     * @param param param
     * @return {@link GithubAddressTypeEnum }
     */
    @Override
    public GithubObtainInfoVo getInfo(GithubBaseParam param) throws GitAPIException, IOException {
        CheckUtil.checkStrNotBlank(param.getGithubAddress(), new RuntimeException("github地址不能为空"));
        GithubObtainInfoVo githubObtainInfoVo = OwnGithubUtil.obtainGithubUrlInfo(param.getGithubAddress());
        if (githubObtainInfoVo.toTypeEnum() == GithubAddressTypeEnum.HAS_BRANCH_REPOSITORY || githubObtainInfoVo.toTypeEnum() == GithubAddressTypeEnum.NO_BRANCH_REPOSITORY) {
            String defaultBranch = OwnGithubUtil.getDefaultBranch(param.getGithubAddress());
            githubObtainInfoVo.setBranchName(defaultBranch);
        }
        return githubObtainInfoVo;
    }

    /**
     * 获取该github的所有分支
     *
     * @param param param
     * @return {@link List }<{@link String }>
     */
    @Override
    public List<GithubGetBranchListVO> getBranches(GithubBaseParam param) throws GitAPIException, IOException {
        Git git = OwnGithubUtil.initGit(param.getGithubAddress());
        GitUtils.closeGit(git);
        List<GitBranchesDTO> branches = GitUtils.getBranches(git, GitBranchType.REMOTE);
        ArrayList<GithubGetBranchListVO> data = Lists.newArrayList();

        //拼接带分支地址
        for (GitBranchesDTO remoteBranch : branches) {
            String branchUrl = OwnGithubUtil.getBranchUrl(param.getGithubAddress(), remoteBranch.getBranchName());
            data.add(new GithubGetBranchListVO(remoteBranch.getBranchName(), branchUrl, remoteBranch.getDefaultFlag()));
        }
        return data;
    }


    /**
     * 下载
     *
     * @param param param
     * @return {@link String }
     */
    @Override
    public String download(GithubBaseParam param) throws GitAPIException, IOException {
        CheckUtil.checkStrNotBlank(param.getGithubAddress(), new RuntimeException("github地址不能为空"));
        String fileName = OwnFileUtil.getLastPath(param.getGithubAddress());
        CredentialsProvider credential = GitUtils.createCredentialsProvider("", "");
        String localPath = OwnFileUtil.getLocalPath(LocalDirEnum.GITHUB, fileName);
        Git git = GitUtils.getGit(param.getGithubAddress(), credential, localPath);
        GitUtils.closeGit(git);
        String zipFileName = fileName + ".zip";
        File zip = ZipUtil.zip(localPath, zipFileName);
        FileUtil.copy(zip.getAbsolutePath(), OwnFileUtil.getDownloadPath(LocalDirEnum.GITHUB, zipFileName), true);
        return OwnFileUtil.getDownloadUrl(LocalDirEnum.GITHUB, zipFileName);
    }

    /**
     * 下载 zip
     *
     * @param param param
     * @return {@link String }
     */
    @Override
    public String downloadZip(GithubBaseParam param) throws GitAPIException, IOException {
        GithubObtainInfoVo githubObtainInfoVo = OwnGithubUtil.obtainGithubUrlInfo(param.getGithubAddress());
        String branch = "";
        //如果不是有分支的代码仓库，则获取默认分支
        if (githubObtainInfoVo.toTypeEnum() == GithubAddressTypeEnum.NO_BRANCH_REPOSITORY) {
            //获取所有分支
            List<String> allBranch = OwnGithubUtil.getAllBranch(param.getGithubAddress());
            if (StrUtil.isEmpty(param.getBranchName())) {
                //如果没有传分支 那么获取默认分支
                branch = OwnGithubUtil.getDefaultBranch(param.getGithubAddress());
            } else {
                //先校验分支是否存在
                CheckUtil.checkTrue(allBranch.contains(param.getBranchName()), new CommonException("该分支不存在"));
                branch = param.getBranchName();
            }
        } else if (githubObtainInfoVo.toTypeEnum() == GithubAddressTypeEnum.HAS_BRANCH_REPOSITORY) {
            //链接本身已经规定好了分支
            String branchName = githubObtainInfoVo.getBranchName();
            List<String> allBranch = OwnGithubUtil.getAllBranch(param.getGithubAddress());
            CheckUtil.checkTrue(allBranch.contains(branchName), new CommonException("该分支不存在"));
            branch = branchName;
        }
        CheckUtil.checkStrNotBlank(branch, new RuntimeException("分支不能为空"));
        //获取github的下载地址
        String downloadUrl = OwnGithubUtil.genetateGithubDownloadUrl(githubObtainInfoVo, branch);
        //获取本地路径
        String lastPath = OwnFileUtil.getLastPath(param.getGithubAddress());
        String downloadPath = OwnFileUtil.getLocalPath(LocalDirEnum.GITHUB, lastPath);
        File file = HttpDownloader.downloadFile(downloadUrl, FileUtil.newFile(downloadPath));
        FileUtil.copy(file, OwnFileUtil.getDownloadPathFile(LocalDirEnum.GITHUB, file.getName()), true);
        return OwnFileUtil.getDownloadUrl(LocalDirEnum.GITHUB, file.getName());
    }

}
